# -*- coding: utf-8 -*-
"""
"""
import datetime

import jwt

from pyshare.dal.gameconfig.game_env import get_config_env_set
from pyshare.dal.repository_impl import RoleRepository
from pyshare.core.context import temporary_ctx


def auth(rid, secret, token_exp):
    """
    对角色进行验证,获得token

    因为游戏内的请求已经经过帐号验证,会话验证,因此只判断角色是否存在

    token只要携带以下信息:
      * app_id
      * server_id
      * rid
      * exp 过期时间

    统一使用HS256算法

    :param int app_id:
    :param int server_id:
    :param str rid:
    """
    payload = {
        "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=token_exp),
        "rid": rid,
    }

    token = jwt.encode(
        payload=payload,
        key=secret,
        algorithm="HS256",
    )

    return token


def auth_verify(token, secret):
    """
    验证token的有效性

    :param str token:
    """
    payload = jwt.decode(
        jwt=token,
        key=secret,
        algorithms=["HS256"],
    )

    return payload.get("rid")
